import React, { Component, Fragment } from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';

import _ from 'lodash';
import qs from 'qs';

import { addTab } from '@/utils/utils';
import { Form } from '@ant-design/compatible';
import PageHeader from '@/components/PageHeader';
import { FormComponentProps } from '@ant-design/compatible/es/form';

import {
  Row,
  Col,
  Card,
  Table,
  Select,
  Button,
} from 'antd';
import '@ant-design/compatible/assets/index.css';

const { Option } = Select;
const { pathname } = window.location;

interface CabinetDeliveryChargeDetailInfoProps extends FormComponentProps {
  dispatch: Dispatch;
  dataInfo: any;
  INITINFO: any;
  screen: string;
  location: {
    query: {
      uid?: number;
    };
  };
}

interface CabinetDeliveryChargeDetailInfoState {
  searchValues: any;
  pageIndex: number;
  pageSize: number;
  rowId:number;
}

@connect(
  ({
    CabinetDeliveryDetail: { dataInfo },
    common: { INITINFO }, global: { screen },
  }: any) => ({
    dataInfo,
    INITINFO,
    screen,
  }),
)
class CabinetDeliveryChargeDetailInfoElem extends Component<CabinetDeliveryChargeDetailInfoProps,
CabinetDeliveryChargeDetailInfoState> {
  columns: any = [
    { title: 'ID', dataIndex: 'id' },
    { title: '目的地', dataIndex: 'toPname' },
    {
      title: '首重(元)',
      dataIndex: 'firstPrice',
      render: (text: any) => (text / 100).toFixed(2),
    },
    {
      title: '续重(元)',
      dataIndex: 'additionalPrice',
      render: (text: any) => (text / 100).toFixed(2),
    },
    { title: '格口类型', dataIndex: 'cellTypeName' },
    { title: '快递公司', dataIndex: 'expressName' },
    {
      title: '运费(元)',
      dataIndex: 'price',
      align: 'center',
      render: (text: any) => (text / 100).toFixed(2),
    },
    {
      title: '时效(天)',
      dataIndex: 'arriveTime',
      align: 'center',
      render: (text: any) => (text / 24).toFixed(0),
    },
  ];

  state: CabinetDeliveryChargeDetailInfoState = {
    searchValues: {},
    pageIndex: 1,
    pageSize: 20,
    rowId: 0,
  };

  static getDerivedStateFromProps(nextProps: any, preState: any) {
    const { location: { query } } = nextProps;
    const { pageIndex, pageSize, ...searchValues } = query;
    return {
      searchValues,
      pageIndex: Number(pageIndex) || 1,
      pageSize: Number(pageSize) || (nextProps.screen === 'sm' ? 100 : 20),
    };
  }

  componentDidMount() {
    this.setFieldsValue();
    this.fetchDataValues();
    this.fetchAction('common/fetchAreaList');
  }

  componentDidUpdate(prevProps: any, prevState: any) {
    const { searchValues, pageIndex, pageSize } = this.state;
    const { location: { query: { uid } } } = this.props;
    if (!_.isEqual(searchValues, prevState.searchValues)
      || pageIndex !== prevState.pageIndex
      || pageSize !== prevState.pageSize
      || uid !== prevProps.location.query.uid
    ) {
      this.setFieldsValue();
      this.fetchDataValues();
    }
  }

  setFieldsValue = () => {
    // 设置表单
    const { searchValues } = this.state;
    const { toPcode, cellType } = searchValues;
    const { form: { setFieldsValue } } = this.props;
    setFieldsValue({ toPcode, cellType });
  };

  fetchDataValues = () => this.fetchAction('fetch', this.getQueryParams());

  getQueryParams = () => {
    const { searchValues, pageIndex, pageSize } = this.state;
    const params = {
      ...searchValues,
      pageIndex,
      pageSize,
    };
    return params;
  };

  onSelectChange = (pageIndex: number, pageSize: number) => {
    const { searchValues }: any = this.state;
    const query = {
      ...searchValues,
      pageIndex,
      pageSize,
    };

    const { dispatch } = this.props;
    addTab(dispatch, {
      name: `查看${searchValues.uid}`,
      url: `${pathname}?${qs.stringify(query)}`,
      isTopMenu: true,
    });
  };

  handleSearch = (e: React.FormEvent) => {
    e.preventDefault();

    const { form: { validateFields } } = this.props;
    validateFields((errors, values) => {
      if (errors) return;

      const { searchValues }: any = this.state;
      const query = { ...searchValues, ...values };

      const { dispatch } = this.props;
      addTab(dispatch, {
        name: `查看${searchValues.uid}`,
        url: `${pathname}?${qs.stringify(query)}`,
        isTopMenu: true,
      });
    });
  };

  handleReset = () => {
    const { form: { resetFields } } = this.props;
    resetFields();

    const { searchValues: { uid } } = this.state;
    const query = { uid };
    const { dispatch } = this.props;
    addTab(dispatch, {
      name: `查看${uid}`,
      url: `${pathname}?${qs.stringify(query)}`,
      isTopMenu: true,
    });
  };

  onClickRow = ({ id }: any) => ({
    onClick: () => {
      this.setState({ rowId: id });
    },
  })

  setRowClassName = ({ id }: any) => {
    const { rowId } = this.state;
    return id === rowId ? 'clickRowStyl' : '';
  }

  fetchAction = (typeName: string, payload: any = {}) => {
    const type = typeName.indexOf('common') >= 0
      ? typeName : `CabinetDeliveryDetail/${typeName}`;
    const { dispatch } = this.props;
    dispatch({ type, payload });
  };

  render() {
    const { pageIndex, pageSize } = this.state;
    const {
      form: { getFieldDecorator },
      INITINFO: { areaList },
      dataInfo,
    } = this.props;

    const dataSource = dataInfo ? dataInfo.list : [];
    const pagination: object = dataInfo
      ? {
        total: dataInfo.count,
        current: pageIndex,
        pageSize,
        showQuickJumper: true,
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '50', '100'],
        showTotal: () => `共${dataInfo.count || 0}条数据`,
        onChange: this.onSelectChange,
        onShowSizeChange: this.onSelectChange,
      }
      : {};

    return (
      <Fragment>
        <PageHeader />

        <Card bordered={false} className="searchForm">
          <Form
            className="tableListForm"
            onSubmit={this.handleSearch}
          >
            <Row gutter={12}>
              <Col md={6} sm={24}>
                <Form.Item label="选择省份" colon={false}>
                  {getFieldDecorator('toPcode')(
                    <Select placeholder="请选择">
                      {areaList.map((item: any) => (
                        <Option key={String(item.id)} value={item.code}>
                          {item.name}
                        </Option>
                      ))}
                    </Select>,
                  )}
                </Form.Item>
              </Col>
              <Col md={6} sm={24}>
                <Form.Item label="格口类型" colon={false}>
                  {getFieldDecorator('cellType')(
                    <Select
                      showSearch
                      placeholder="请选择"
                      filterOption={(input: any, option: any) => (
                        option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                      )}
                    >
                      <Option value="0">全部</Option>
                      <Option value="10912">超大(宽)箱</Option>
                      <Option value="10901">大箱</Option>
                      <Option value="10902">中箱</Option>
                      <Option value="10903">小箱</Option>
                      <Option value="10904">超小箱</Option>
                      <Option value="10905">大(宽)箱</Option>
                      <Option value="10906">中(宽)箱</Option>
                      <Option value="10907">小(宽)箱</Option>
                      <Option value="10908">超小(宽)箱</Option>
                      <Option value="10909">文件箱</Option>
                      <Option value="10910">文件(宽)箱</Option>
                      <Option value="10911">超大箱</Option>
                    </Select>,
                  )}
                </Form.Item>
              </Col>
              <Col md={12} sm={24}>
                <div className="flexFeView">
                  <Button
                    type="primary"
                    htmlType="submit"
                    className="smallButton"
                  >
                    查询
                  </Button>
                  <Button
                    className="addButton smallButton marginL16"
                    type="primary"
                    onClick={this.handleReset}
                  >
                    重置
                  </Button>
                </div>
              </Col>
            </Row>
          </Form>
        </Card>

        <Card bordered={false} className="tableList">
          <Table
            rowKey="id"
            tableLayout="fixed"
            className="statementTable tableHeight60"
            columns={this.columns}
            dataSource={dataSource}
            pagination={pagination}
            scroll={{ x: 980 }}
            onRow={this.onClickRow}
            rowClassName={this.setRowClassName}
          />
        </Card>
      </Fragment>
    );
  }
}

export default Form.create<any>()(CabinetDeliveryChargeDetailInfoElem);
